package com.dycong.common.common;

/**
 * Created by Duke on 2016/9/14.
 */

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static String byteArrayToHexString(byte b[]) {
        StringBuilder resultSb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    private static final String HEX_DIGITS[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * 字符串加密为16进制数据
     * @param origin
     * @param charsetname
     * @return
     */
    public static String md5encode(String origin, String charsetname) {
        String resultString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
            }
        } catch (Exception exception) {

        }
        return resultString;
    }

    /**
     * 字符串加密为二进制数据
     * @param origin
     * @param charsetname
     * @return
     */
    public  static byte[] getMD5Str(String str) {
        MessageDigest messageDigest = null;

        try {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return messageDigest.digest();


    }



    public static void main(String[] args) {
        String s = "123456";
//        System.out.println(getMD5Str(s));
        byte [] temp = getMD5Str(s);


        System.out.println(byteArrayToHexString(temp));
        System.out.println(byteToString(temp));
        System.out.println(new BASE64Encoder().encode(getMD5Str(s)));
    }

    private static String byteToString(byte[] bytes){
        StringBuilder stringBuffer=new StringBuilder();
        for (byte b : bytes) {
            stringBuffer.append(b);
        }
        return stringBuffer.toString();
    }

}
